package com.time.auth.application.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.base.Preconditions;
import com.time.auth.application.convent.AuthPermissionDTOConverter;
import com.time.auth.application.dto.AuthPermissionDTO;
import com.time.auth.domain.constants.AuthConstant;
import com.time.auth.domain.entity.AuthPermissionBO;
import com.time.auth.domain.service.AuthPermissionDomainService;
import com.time.auth.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 权限控制层类
 *
 * @author: HuangQi
 * @date: Created in 14:56 2025/9/18
 * @description: 权限控制层
 */
@RestController
@RequestMapping("/permission/")
@Slf4j
public class PermissionController {

    @Autowired
    private AuthPermissionDomainService authPermissionDomainService;

    /**
     * 新增权限
     *
     * @param authPermissionDTO 新增权限的信息
     * @return 新增结果
     */
    @PostMapping("add")
    public Result<Boolean> add(@RequestBody AuthPermissionDTO authPermissionDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("PermissionController.add.dto:{}", authPermissionDTO);
            }
            // 参数校验
            Preconditions.checkArgument(!StringUtils.isBlank(authPermissionDTO.getName()), "权限名称不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(authPermissionDTO.getPermissionKey()), "权限唯一标识不能为空");
            Preconditions.checkNotNull(authPermissionDTO.getParentId(), "权限父id不能为空");
            Preconditions.checkNotNull(authPermissionDTO.getType(), "权限类型不能为空");

            // 调用领域层
            AuthPermissionBO authPermissionBO = AuthPermissionDTOConverter.INSTANCE.convertDTOToBO(authPermissionDTO);
            Boolean registerResult = authPermissionDomainService.add(authPermissionBO);

            // 返回结果
            return Result.ok(registerResult);
        } catch (Exception e) {
            // 异常处理
            log.error("PermissionController.add.error:{}", e.getMessage(), e);
            return Result.fail("新增权限失败");
        }

    }

    /**
     * 更新权限
     *
     * @param authPermissionDTO 更新权限的信息
     * @return 更新结果
     */
    @PostMapping("update")
    public Result<Boolean> update(@RequestBody AuthPermissionDTO authPermissionDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("PermissionController.update.dto:{}", authPermissionDTO);
            }
            // 参数校验
            Preconditions.checkNotNull(authPermissionDTO.getId(), "权限id不能为空");

            // 调用领域层
            AuthPermissionBO authPermissionBO = AuthPermissionDTOConverter.INSTANCE.convertDTOToBO(authPermissionDTO);
            Boolean updateResult = authPermissionDomainService.update(authPermissionBO);

            // 返回结果
            return Result.ok(updateResult);
        } catch (Exception e) {
            // 异常处理
            log.error("PermissionController.update.error:{}", e.getMessage(), e);
            return Result.fail("更新权限失败");
        }

    }

    /**
     * 删除权限（逻辑删除）
     *
     * @param authPermissionDTO 删除权限的信息
     * @return 删除结果
     */
    @PostMapping("delete")
    public Result<Boolean> delete(@RequestBody AuthPermissionDTO authPermissionDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("PermissionController.delete.dto:{}", authPermissionDTO);
            }
            // 参数校验
            Preconditions.checkNotNull(authPermissionDTO.getId(), "权限id不能为空");

            // 调用领域层
            AuthPermissionBO authPermissionBO = AuthPermissionDTOConverter.INSTANCE.convertDTOToBO(authPermissionDTO);
            Boolean deleteResult = authPermissionDomainService.delete(authPermissionBO);

            // 返回结果
            return Result.ok(deleteResult);
        } catch (Exception e) {
            // 异常处理
            log.error("PermissionController.delete.error:{}", e.getMessage(), e);
            return Result.fail("删除权限失败");
        }

    }

    /**
     * 获取用户权限
     *
     * @param userName 用户名
     * @param userType 用户类别
     * @return 用户权限列表
     */
    @GetMapping("getPermission")
    public Result<String> getPermission(@RequestParam String userName, @RequestParam String userType) {
        try {
            if (log.isInfoEnabled()) {
                log.info("PermissionController.getPermission.userName:{}, userType:{}", userName, userType);
            }
            // 参数校验
            Preconditions.checkArgument(!StringUtils.isBlank(userName), "用户名不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(userType), "用户类别不能为空");
            Preconditions.checkArgument(
                    AuthConstant.ADMIN_USER_TYPE.equals(userType) || AuthConstant.NORMAL_USER_TYPE.equals(userType),
                    "用户类别必须是 admin 或 user，当前值：%s", userType
            );

            // 调用领域层
            List<String> permissionList = authPermissionDomainService.getPermission(userName, userType);

            // 返回结果
            return Result.ok(permissionList);
        } catch (Exception e) {
            // 异常处理
            log.error("PermissionController.getPermission.error:{}", e.getMessage(), e);
            return Result.fail("获取用户权限失败");
        }
    }

}
